package com.superbit.web.servlet;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superbit.core.entry.Coin_Base_Info;
import com.superbit.core.entry.User_Withdraw;
import com.superbit.core.service.UserMessageProxy;
import com.superbit.core.tools.PageListRes;
import com.superbit.service.coin.define.Coin_Base_InfoService;
import com.superbit.service.userasset.service.define.User_AssetService;
import com.superbit.service.withdraw.service.define.User_WithdrawService;
import com.superbit.web.excep.ErrorCodeConstant;
import com.superbit.web.listener.ServiceBeanFactory;
import com.superbit.web.utils.JsonResponseUtil;
import com.superbit.web.utils.StringPropertiesUtil;

@Controller
@RequestMapping("/withdraw.act")
public class UserWithDrawController {
	
	private static Logger logger = LoggerFactory.getLogger(UserWithDrawController.class);
	
	
	private User_WithdrawService user_WithdrawService;
	private UserMessageProxy userMessageProxy;
//	private UserSafeInfoProxy userSafeInfoProxy;
	private User_AssetService user_AssetService;
	private Coin_Base_InfoService cbiService;
	
	@PostConstruct
	private void init(){
		user_WithdrawService = ServiceBeanFactory.getBean(User_WithdrawService.class);
		userMessageProxy = ServiceBeanFactory.getBean(UserMessageProxy.class);
//		userSafeInfoProxy = ServiceBeanFactory.getBean(UserSafeInfoProxy.class);
		user_AssetService = ServiceBeanFactory.getBean(User_AssetService.class);
		cbiService = ServiceBeanFactory.getBean(Coin_Base_InfoService.class);
	}
	
	
	
	
	/**
	 * 用户发送验证码请求
	 * @param session
	 * @param request
	 * @param assetId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=sendSMS")
	public String sendSMS(HttpSession session, HttpServletRequest request){
		logger.info("sendSMS");

		Integer userId = StringPropertiesUtil.getUserId(session);
		

		boolean flag = userMessageProxy.sendSMS(userId, "withdraw");
		flag = true;
		if(flag) {
			return JsonResponseUtil.buildSucessResonpe("ok").toString();
		}else {
			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.VERIFICATIONCODE, "error").toString();
		}
	}
	
	/**
	 * 用户提现
	 *    密码等验证
	 *    提现记录保存
	 *    资产变动保存
	 * @param session
	 * @param request
	 * @param assetId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=verficationWithDraw")
	public String verficationWithDraw(HttpSession session, HttpServletRequest request,
			String smsCode,
			String fundPwd,
			String googleCode,
			String assetId,
			String coinId,
			String withDrawPlat,
			String withDrawAddr,
			String serviceCharge,
			String withDrawAmount){
		logger.info("verficationWithDraw");
		boolean flag = true;
		Integer userId = StringPropertiesUtil.getUserId(session);
//		UserSafeInfo usi = userSafeInfoProxy.verificationSafeInfo(userId);
		if(null!=googleCode && googleCode.length()>0) {//谷歌验证
//			flag = GoogleAuthUtils.authcode(googleCode, usi.getGooglePrivateKey());
			if(flag) {
			}else {
				return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.VERIFICATIONCODE, "谷歌验证码错误").toString();
			}
		}else {//短信验证
//			flag = userMessageProxy.verficationSMS(userId, "withdraw", smsCode);
			if(flag) {}else {
				return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.VERIFICATIONCODE, "短信验证码错误").toString();
			}
		}
		
//		if(usi.getFundPassword().equals(fundPwd)) {}else {//资金密码验证
//			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.VERIFICATIONCODE, "资金密码错误").toString();
//		}
//		if(usi.getFreezeDeadline().before(new Date())) {
//			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.FREEZDATE, "请在修改密码24小时后进行提现操作").toString();
//		}
		
		// 提现额度判断，是否在当前币种每日提现额度内，需要从提现记录中统计今天提现数量
		BigDecimal bigDecimal = user_WithdrawService.getWithDrawsLimit(userId, assetId, coinId, null);
		bigDecimal = bigDecimal.add(new BigDecimal(withDrawAmount));
		Coin_Base_Info cbi = cbiService.getCoin_Base_InfoList(3, coinId, null, null).get(0);
		if(bigDecimal.compareTo(cbi.getCoinLimitMin())==-1) {
			//小于
			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.WITHDRAWMIN, "提现金额小于该币种最小提现额度").toString();
		}
		if(bigDecimal.compareTo(cbi.getCoinLimitMax())==1) {
			//大于
			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.WITHDRAWMAX, "提现金额大于该币种最大提现额度").toString();
		}
		//TODO  提现操作
		// 1. 冻结资产
		// 2. 保存提现记录
		try {
			user_AssetService.updateUser_Asset_Amount(userId, 0, coinId, null, new BigDecimal(withDrawAmount));
			Coin_Base_Info coin_Base_Info = cbiService.getCoin_Base_InfoList(3, coinId, null, null).get(0);
			User_Withdraw uw = new User_Withdraw();
			uw.setUserId(userId);
			uw.setAssetId(assetId);
			uw.setCoinId(coinId);
			uw.setCoinName(coin_Base_Info.getCoinName());//获取币种名称
			uw.setArea(coin_Base_Info.getArea());
			uw.setWithDrawPlat(withDrawPlat);
			uw.setWithDrawAddr(withDrawAddr);
			uw.setWithDrawAmount(new BigDecimal(withDrawAmount));
			uw.setServiceCharge(new BigDecimal(serviceCharge));
			uw.setWithDrawStatus(0);
			uw.setCreateTime(new Date());
			
			user_WithdrawService.saveUser_Withdraw(uw);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.VERIFICATIONCODE, "error").toString();
		}
		
		if(flag) {
			return JsonResponseUtil.buildSucessResonpe("ok").toString();
		}else {
			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.VERIFICATIONCODE, "error").toString();
		}
	}
	
	/**
	 * 获取用户提现记录
	 * @param session
	 * @param request
	 * @param coinId
	 * @param status  提现状态
	 * @param stime
	 * @param etime
	 * @param pageNo
	 * @param pageSize
	 * @param order
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=getUser_WithDraws")
	public String getUser_WithDraws(HttpSession session, HttpServletRequest request,
			String coinId,
			int status,
			String stime,
			String etime,
			int pageNo,
			int pageSize,
			String order
			) {
		logger.info("getUser_WithDraws");
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date sDate = null;
		Date eDate = null;
		try {
			sDate = stime.length()==19?simpleDateFormat.parse(stime):null;
			eDate = etime.length()==19?simpleDateFormat.parse(etime):null;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Integer userId = StringPropertiesUtil.getUserId(session);
		PageListRes<User_Withdraw> result = new PageListRes<User_Withdraw>();
		result.setPageSize(pageSize);
		result.setPageNo(pageNo);
		result.setTotal(user_WithdrawService.getUser_WithdrawCount(userId, coinId, status, sDate, eDate));
		List<User_Withdraw> user_Withdraws = null;
		if(result.getTotal()>0) {
			user_Withdraws = user_WithdrawService.getUser_Withdraws(userId, coinId, status, sDate, eDate, (pageNo-1)*pageSize, pageSize, order);
		}
		result.setList(user_Withdraws);
		return JsonResponseUtil.buildSucessResonpe(result).toString();
	}
	
	/**
	 * 获取用户提现地址？？？？？
	 * @param session
	 * @param request
	 * @param assetId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=getUser_WithDrawAddr")
	public String getUser_WithDrawAddr(HttpSession session, HttpServletRequest request,
			String assetId){
		logger.info("getUser_WithDrawAddr");

		Integer userId = StringPropertiesUtil.getUserId(session);
		

		boolean flag = userMessageProxy.sendSMS(userId, "withdraw");
		flag = true;
		if(flag) {
			return JsonResponseUtil.buildSucessResonpe("ok").toString();
		}else {
			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.VERIFICATIONCODE, "error").toString();
		}
	}
	
	/**
	 * 修改用户提现状态
	 * @param session
	 * @param request
	 * @param id  数据库中自增id
	 * @param withDrawStatus
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=updateUser_WithDrawStatus")
	public String updateUser_WithDrawStatus(HttpSession session, HttpServletRequest request,
			int id,
			String assetId,
			String coinId,
			int withDrawStatus
			){
		logger.info("updateUser_WithDrawStatus");

		Integer userId = StringPropertiesUtil.getUserId(session);
		
		try {
			User_Withdraw user_Withdraw = user_WithdrawService.getUser_Withdraw(id);
			
			if(user_Withdraw.getUserId()==userId&&user_Withdraw.getAssetId().equals(assetId)
					&&user_Withdraw.getCoinId().equals(coinId)) {
				System.out.println(user_Withdraw.getWithDrawStatus()+"    "+withDrawStatus);
				user_Withdraw.setWithDrawStatus(withDrawStatus);
				user_WithdrawService.updateUser_Withdraw(user_Withdraw);
				return JsonResponseUtil.buildSucessResonpe("ok").toString();
			}else {
				return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.WITHDRAWSTATUSERROR, "非法修改提现状态").toString();
			}
		} catch (Exception e) {
			// TODO: handle exception
			return JsonResponseUtil.buildNormalExcepResonpe(ErrorCodeConstant.WITHDRAWSTATUSFAIL, "提现状态修改失败").toString();
		}
		

	}
}
